<template>
	<div class="user">
		<el-container class="el-container">
		      <el-aside width="200px">
				  <el-input  size="small"   class="selectDept" placeholder="请输入部门模糊查询" v-model="filterText"></el-input>
				  <el-tree class="el-tree" ref="treeRef"
				      :data="dataDept"
				      :props="defaultDeptProps"
					  default-expand-all
					  :filter-node-method="filterNode"
				      @node-click="handleDeptNodeClick"
				  />
			  </el-aside>
			  <el-main class="el-main">
			  	<div class="allcontent">
					  <div class="search">
						<el-form @submit.native.prevent ref="queryFormRef"  :model="searchParam" >
							<el-row gutter="10">
								<el-col span="8">
									<el-form-item  prop="userName">
									      <el-input  size="small"   @keyup.enter.native="search" placeholder="请输入账号模糊搜索" autofocus v-model="searchParam.userName"></el-input>
									</el-form-item>
								</el-col>
								<el-col  span="8">
									<el-form-item  prop="phone">
										<el-input  size="small"   @keyup.enter.native="search" placeholder="请输入手机号模糊搜索"  v-model="searchParam.phone"></el-input>
									</el-form-item>
								</el-col>
								<el-col  span="8">
									<el-button size="small"  plain icon="Search"  type="primary" @click="search">搜索</el-button>
								</el-col>
								<el-col  span="8">
									<el-button  size="small"  plain icon="Refresh" type="warning" @click="reset(queryFormRef)">重置</el-button>
								</el-col>
							</el-row>
							<el-row gutter="10" style="margin-bottom: 10px;">
								<el-col span="8" v-if="userStore.hasPermission('system:user:add')">
									<el-button  size="small"  plain icon="Edit"  type="success" @click="addUser()">新增</el-button>
								</el-col>
								<el-col span="8"  v-if="userStore.hasPermission('system:user:edit')">
									<el-button  size="small"  plain icon="Edit"  type="primary" @click="editUser()" :disabled="selections.length > 1||  selections.length == 0?true:false">编辑</el-button>
								</el-col>
								<el-col span="8" v-if="userStore.hasPermission('system:user:delete')">
									<el-popconfirm
									    confirm-button-text="确认"
									    cancel-button-text="取消"
									    :icon="InfoFilled"
									    icon-color="#626AEF"
									    title="是否确认删除这些数据？"
									    @confirm="removeUsers()"
									  >
									    <template #reference>
									      <el-button  size="small"  plain icon="Delete"  :disabled="selections.length == 0?true:false"  type="danger" >删除</el-button>
									    </template>
									</el-popconfirm>
								</el-col>
                <el-col :span="1.5">
                  <el-button
                      type="info"
                      plain
                      icon="Upload"
                      size="small"
                      @click="handleImport"
                  >导入</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                      type="warning"
                      plain
                      icon="Download"
                      size="small"
                      @click="handleExport"
                  >导出</el-button>
                </el-col>
							</el-row>
						</el-form>
					  </div>
					  <div class="el-table">
						<el-table ref="tableRef" v-loading="loading" :data="tableData" style="width: 100%;font-size:13px;" @selection-change="handleSelectionChange">
							<el-table-column type="selection" width="55" :selectable="selectData"></el-table-column>
							<el-table-column prop="userName" label="账号" width="180" />
							<el-table-column prop="nickName" label="昵称" width="180" />
							<el-table-column prop="deptName" label="部门" />
							<el-table-column prop="phone" label="手机号" />
							<el-table-column prop="status" label="状态">
								<template  #default="scope">
									<el-tag v-if="scope.row.status == 1">正常</el-tag>
									<el-tag type="danger" v-else-if="scope.row.status == 0">禁用</el-tag>
								</template>
							</el-table-column>	
							<el-table-column  label="操作" width="300">
								<template  #default="scope">
									<el-button   plain icon="Edit" v-if="userStore.hasPermission('system:user:edit')" size="small" type="primary" @click="editUser(scope.row.id)">编辑</el-button>
									<el-popconfirm  v-if="userStore.hasPermission('system:user:delete') && scope.row.id !=1"
										confirm-button-text="是"
										cancel-button-text="否"
										:icon="InfoFilled"
										icon-color="#626AEF"
										title="是否删除该数据?"
										@confirm="removeUsers(scope.row.id)"
									  >
										<template #reference>
										  <el-button   plain icon="Delete"  size="small" type="danger">
											  删除
										  </el-button>
										</template>
									</el-popconfirm>
									<el-button  plain icon="Operation" v-if="userStore.hasPermission('system:user:edit') && scope.row.id !=1" size="small" type="warning" @click="editPassword(scope.row)">重置密码</el-button>
								</template>
							</el-table-column>
						</el-table>
					  </div>
					  <div class="el-pager">
						 <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total" 
						 :page-sizes="[10,20,30,40,50]" :pager-count="11"
						 size="small"  background  class="mt-4" :current-page="currentPage" 
						 @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
					  </div>
			  		<el-drawer  size="40%" v-model="addUserDialog" title="新增" width="50%">
			  			<AddUser  @closeAddUserForm="closeAddUserForm" @success="success"></AddUser>
			  		</el-drawer>
			  		<el-drawer  size="40%" v-model="editUserDialog" title="编辑" width="50%">
			  			<EditUser :userId="userId"  @closeEditUserForm="closeEditUserForm" @success="success"></EditUser>
			  		</el-drawer>
            <!-- 用户导入对话框 -->
            <el-dialog :title="uploadTitle" v-model="uploadOpen" width="400px" append-to-body>
              <el-upload
                  ref="upload"
                  :limit="1"
                  accept=".xlsx"
                  :headers="headers"
                  :action="uploadUrl + '?updateSupport=' + updateSupport"
                  :on-progress="handleFileUploadProgress"
                  :on-success="handleFileSuccess"
                  :auto-upload="false"
                  drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                  <div class="el-upload__tip" slot="tip">
                    <el-checkbox @change="updateSupportChangeValue" @click.stop="updateSupportChange"/> 是否更新已经存在的用户数据
                  </div>
                  <span>仅允许导入xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click.stop="importTemplate">下载模板</el-link>
                </div>
              </el-upload>
              <div slot="footer" class="dialog-footer">
                <el-button size="small" plain icon="Upload" type="primary" @click.stop="submitFileForm">确 定</el-button>
                <el-button size="small"  plain icon="Close" @click.stop="uploadOpen = false">取 消</el-button>
              </div>
            </el-dialog>
			  	</div>				  
			  </el-main>
		</el-container>
	</div>
</template>

<script setup lang="ts">
	import {ref,reactive,watch,onMounted} from 'vue'
	import AddUser from './AddUser.vue'
	import EditUser from './EditUser.vue'
	import {ElMessage,ElMessageBox,ElTree,ElTable } from 'element-plus'
	import type { FormInstance, FormRules } from 'element-plus'
	import { page,remove,edit,exportUser } from '@/api/user.ts';
	import {treelist} from '@/api/dept.ts'
	import {useUserStore} from '@/stores/user.ts'
	import {downloadFile} from '@/api/upload.ts'
  const userStore = useUserStore()
  const token = userStore.token
  const headers = ref({
    'Authorization':token
  })
  const updateSupportChange=(e)=>{
    console.log("haode"+JSON.stringify(e))
  }
  const updateSupportChangeValue=(e)=>{
    console.log("haode2"+e)
    if (e){
      updateSupport.value=1;
    }else{
      updateSupport.value=0;
    }
  }
  const updateSupport=ref(0)
  const uploadUrl = ref('/api/system/user/import')
  const upload=ref()
  const uploadTitle=ref()
  const uploadOpen=ref(false)
  const isUploading=ref(false)
  const handleImport=()=> {
    uploadTitle.value = "用户导入";
    uploadOpen.value = true;
  }
  // 文件上传中处理
  const handleFileUploadProgress=(event, file, fileList)=> {
    isUploading.value = true;
  }
  // 文件上传成功处理
  const handleFileSuccess=(response, file, fileList)=> {
    uploadOpen.value = false;
    isUploading.value = false;
    upload.value.clearFiles();
    alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    loadData()
  }
  // 提交上传文件
  const submitFileForm=()=> {
    upload.value!.submit()
  }
  const importTemplate=()=>{
    downloadFile({"filePath":'/profile/2025/4/21/1745240970472.xlsx'}).then(res =>{
      console.log("res:"+res)
    })
  }
  const handleExport=()=> {
    exportUser({}).then(res =>{
      const fileName = decodeURI(
          `user_template_${new Date().getTime()}.xlsx`
      );
      const blob = new Blob([res.data]);
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = fileName;
      a.click();
      window.URL.revokeObjectURL(url);
    })
  }
	const selectData=(row: any, index: number)=>{
		if(row.id === 1){
			return false;
		}
		return true;
	}

	interface Tree{
		id:number,
		label:string,
		children?:Tree[]
	}
	const filterText = ref('')
	const handleDeptNodeClick = (data:Tree)=>{
		console.log("点击部门数据:"+data.id);
		searchParam.deptId = data.id
		loadData()
	}
	const treeRef=ref<InstanceType<typeof ElTree>>()
	watch(filterText,(val)=>{
		treeRef.value!.filter(val);
	})
	const filterNode = (value:string,data:Tree)=>{
		if(!value)return true;
		return data.label.includes(value);
	}
	const defaultDeptProps={
		children:'children',
		label:'label'
	}
	
	const searchParam =reactive({
		userName:null,
		phone:null,
		deptId:null,
		page:1,
		limit:10,
	})
	const search=()=>{
		console.log("好的")
		loadData();
	}
	const queryFormRef = ref<FormInstance>()
	const reset = (formEl: FormInstance | undefined) => {
		  if (!formEl) return
		  formEl.resetFields()
		  searchParam.deptId = null
		  loadData();
	}
	
	const tableRef=ref<InstanceType<typeof ElTable>>()
	const selections = ref([])
	const handleSelectionChange=(val)=>{
		selections.value=val;
	}
	
	const tableData = ref([]);
	const total = ref(0);
	const loading=ref(false);
	const loadData =()=>{
		loading.value=true;
		page(searchParam).then((res)=>{
			if(res.code === 200){
				tableData.value = res.data.list;
				total.value = res.data.total;
			}
			loading.value=false;
		})
	}
	
	
	const dataDept=ref([])
	const deptData = () =>{
		treelist({"status":"1"}).then((res)=>{
			if(res.code === 200){
				console.log("：："+res.data)
				dataDept.value = res.data;
			}
		})
	}
	
	onMounted(()=>{
		deptData();
		loadData();
	})
	const currentPage = ref(1)
	const handleSizeChange = (val: number) => {
	  console.log(`${val} items per page`)
	  searchParam.limit= val;
	  loadData();
	}
	const handleCurrentChange = (val: number) => {
	  console.log(`current page: ${val}`)
	  currentPage.value= val;
	  searchParam.page= val;
	  loadData();
	}
	
	const addUserDialog = ref(false);
	const editUserDialog = ref(false);
	
	// 关闭保存用户弹出框
	const closeAddUserForm = ()=> {
	  addUserDialog.value = false
	}
	const closeEditUserForm = ()=> {
	  editUserDialog.value = false
	}
	
	// 提交表单回调函数
	const success = ()=> {
	  addUserDialog.value = false
	  editUserDialog.value = false
	  loadData();
	}
	const userId = ref()
	const addUser=()=>{
		addUserDialog.value = true;
	}
	const removeUsers=async (id:number)=>{
		if(selections.value.length < 0){
			ElMessage({
			  type: 'warning',
			  message: '至少选择一行进行删除',
			})
			return;
		}
		let ids = [];
		if(id != undefined){
			ids.push(id);
		}else{
			selections.value.forEach((item)=>{
				console.log("haode"+item.id)
				ids.push(item.id);
			})
		}
		console.log("ids:"+ids)
		await remove(ids)
		loadData();
	}	
	const editUser=(id:number)=>{
		console.log("修改"+id)
		if(id != undefined){
			userId.value = id;
		}else if(selections.value.length > 0){
			if(selections.value.length > 1){
				ElMessage({
				  type: 'warning',
				  message: '编辑只能选择一行',
				})
				return;
			}
			userId.value = selections.value[0].id
		}else{
			ElMessage({
			  type: 'warning',
			  message: '选择一行进行编辑',
			})
			return;
		}
		editUserDialog.value = true;
		
	}	
	const editPassword=(row:object)=>{
		const id = row.id;
		ElMessageBox.prompt('确认修改账户 "'+row.userName+'"的密码', '修改密码', {
		    confirmButtonText: '确定',
		    cancelButtonText: '取消',
		    inputPattern:
		      /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,}$/,
		    inputErrorMessage: '密码必须至少8个字符，包含大写字母、小写字母和数字',
		  })
		    .then(async ({ value }) => {
			  const formPassword = ref({"id":id,"password":`${value}`})	
			  const {code} = await edit(formPassword.value);
		      if(code === 200){
				  ElMessage({
					type: 'success',
					message: `你的密码是 :${value}`,
				  })
			  }
		    })
		    .catch(() => {
		      ElMessage({
		        type: 'info',
		        message: '取消修改',
		      })
		    })
	}
</script>

<style scoped>
.dialog-footer{
  text-align: center;
}
	.user{

  }
	.el-container{
		/* background-color: gray; */
	}
	.el-main{
		/* background-color: yellow; */
	}
	.search{
		margin-bottom: 10px;
	}
	.el-pager{
    padding: 1%;
    justify-content: right;
		//align-items: right;
		/*position: absolute;
		bottom:0;
		right:0;
		margin-bottom:5px;*/
	}
	.allcontent{
		height: 62vh;
		position: relative;
		/* background-color: blue; */
	}
	.el-table{
		max-height:70%;
		overflow: auto;
	}
	.el-table::-webkit-scrollbar{
		display: none;
	}
	.el-tree{
		padding-top:15px;
		padding-bottom: 15px;
		overflow: scroll;
		height: 50%;
    font-size: 13px;
	}
	.selectDept{
		margin-top:20px;
	}
	.el-tree::-webkit-scrollbar{
		display:none;
	}
</style>